//
//  TPWebViewController.m
//  TPHelper
//
//  Created by xuqiang on 2020/7/23.
//  Copyright © 2020 xuqiang. All rights reserved.
//

#import "TPWebViewController.h"
@import WebKit;
@import Masonry;
@interface TPWebViewController ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic,strong) WKWebView *webView;
@end

@implementation TPWebViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.webView];
    [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://cpu.baidu.com/1085/a54c810d?scid=44855"]];
    [self.webView loadRequest:request];
    
    [_webView addObserver:self forKeyPath:@"URL"options:NSKeyValueObservingOptionNew context:nil];

}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    NSLog(@"***加载的url == %@",_webView.URL.absoluteString);


}
- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        WKPreferences *preference = [[WKPreferences alloc]init];
        preference.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences.javaScriptEnabled = true;
        config.preferences = preference;
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        config.userContentController = wkUController;
        config.allowsInlineMediaPlayback = YES;
        if (@available(iOS 10.0, *)) {
            config.mediaTypesRequiringUserActionForPlayback = NO;
        }
//        config.mediaPlaybackRequiresUserAction = false;
        NSLog(@"%f---%f",kScreenHeight,kNavigationBarHeight);
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavigationBarHeight) configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.allowsBackForwardNavigationGestures = YES;
    }
    return _webView;
}
#pragma mark - WKNavigationDelegate
/**
 *  页面开始加载时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
//    [self startLoading:nil];
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  页面加载完成之后调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
}

/**
 *  加载失败时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 *  @param error      错误
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{

//    if (@available(iOS 12.0, *)) {//iOS11也有这种获取方式，但是我使用的时候iOS11系统可以在response里面直接获取到，只有iOS12获取不到
//        WKHTTPCookieStore *cookieStore = webView.configuration.websiteDataStore.httpCookieStore;
//        [cookieStore getAllCookies:^(NSArray* cookies) {
//            //            [self setCookie:cookies];
//            NSLog(@"+++++%@",cookies);
//        }];
//    }else {
////        NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
////        NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
//        //        [self setCookie:cookies];
//    }
    decisionHandler(WKNavigationResponsePolicyAllow);

}
/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"正在加载的url:%@",navigationAction.request.URL);
    decisionHandler(WKNavigationActionPolicyAllow);

//    if ([navigationAction.request.URL.absoluteString containsString:@"app_"]) {
//        //处理一些跳转
//        [self jumpHandlerWithUrl:navigationAction.request.URL.absoluteString];
//        decisionHandler(WKNavigationActionPolicyCancel);
//    }else if ([navigationAction.request.URL.scheme isEqualToString:@"tel"]) {
//        NSString *resourceSpecifier = [navigationAction.request.URL resourceSpecifier];
//        NSString *callPhone = [NSString stringWithFormat:@"telprompt:%@", resourceSpecifier];
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
//        decisionHandler(WKNavigationActionPolicyCancel);
//
//    }else if ([navigationAction.request.URL.absoluteString containsString:@"jm700qualify"]){
//        [self jumpInitHandlerWithUrl:navigationAction.request.URL.absoluteString];
//        decisionHandler(WKNavigationActionPolicyCancel);
//    }
//    else {
////        decisionHandler(WKNavigationResponsePolicyAllow);
//        decisionHandler(WKNavigationActionPolicyAllow);
//    }
}

@end
